const env = require('./ossUtil/config');
const base64 = require('./ossUtil/base64');
require('./ossUtil/hmac');
require('./ossUtil/sha1');
const Crypto = require('./ossUtil/crypto');

/*
 *上传文件到阿里云oss
 *@param - filePath :文件的本地资源路径
  @param - path :上传oss哪个路径下
 *@param - success:成功回调
 *@param - fail:失败回调
 */
export const uploadAliOssFile = function(filePath, uploadSuccess, uploadFail) {
	//存放文件命名格式
	const aliYunFileKey = clientFileName();
	const aliYunServerURL = env.uploadImageUrl; //OSS地址，https
	const accessID = env.OSSAccessKeyId;
	let policyBase64 = getPolicyBase64();
	let signature = getSignature(policyBase64);
	return uni.uploadFile({
		url: aliYunServerURL, //开发者服务器 url
		filePath: filePath, //要上传文件资源的路径
		name: 'file', //必须填file
		formData: {
			'key': aliYunFileKey,
			'policy': policyBase64,
			'OSSAccessKeyId': accessID,
			'signature': signature,
			'success_action_status': '200',
		},
		success: function(res) {
			if (res.statusCode != 200) {
				fail(new Error('上传错误:' + JSON.stringify(res)))
				return;
			}
			uploadSuccess(aliYunServerURL + aliYunFileKey);
		},
		fail: function(err) {
			err.wxaddinfo = aliYunServerURL;
			uploadFail(err);
		},
	})
}

export function clientPath() {
	const date = new Date();
	let path = date.getFullYear() +
		'/' + padLeft(parseInt(date.getMonth()) + 1,2) +
		'/' + padLeft(date.getDate(), 2) +
		'/';
	return path;
}

export function clientFileName() {
	return clientPath() + uuid() + '.jpg';
}

const getPolicyBase64 = function() {
	let date = new Date();
	date.setHours(date.getHours() + env.timeout);
	let srcT = date.toISOString();
	const policyText = {
		"expiration": srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
		"conditions": [
			["content-length-range", 0, env.maxSize] // 设置上传文件的大小限制,128mb
		]
	};

	const policyBase64 = base64.encode(JSON.stringify(policyText));
	return policyBase64;
}

function izArrayBufferToBase64( buffer ) {
	let binary = '';
	const bytes = new Uint8Array(buffer);
	const len = bytes.byteLength;
	for (let i = 0; i < len; i++) {
		binary += String.fromCharCode( bytes[ i ] );
	}
	let signature = base64.encode(binary)
	return signature
}


const getSignature = function(policyBase64) {
	const accessKey = env.AccessKeySecret;
	const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accessKey, {
		asBytes: true
	});
	const signature=izArrayBufferToBase64(bytes)
	return signature;
}

//获取随机id
const uuid = function(len, binary) {
	len = !len ? 36 : len;
	binary = !binary ? 16 : binary;
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
		var r = Math.random() * binary | 0,
			v = c == 'x' ? r : (r & 0x3 | 0x8);
		return v.toString(binary);
	}).substring(0, len).toUpperCase()
};

//对数字进行前置补位
const padLeft = function(str, length,replaceChar) {
	return ("0000000000000000".replace(/[0]/g,replaceChar||0) + str).substr(-length);
}
